<template>
  <div class="report-configs-page" v-loading="loading">
    <ReportsSearchCard title="搜索与筛选">
      <el-form :model="searchForm" class="search-form">
        <div class="search-form-content">
          <div class="search-form-fields">
            <el-form-item label="报表模板">
              <el-select
                v-model="searchForm.template_code"
                placeholder="选择模板"
                clearable
                style="width: 200px"
                popper-class="batch-dialog-select-popper"
                popper-append-to-body
              >
                <el-option label="全部" value="" />
                <el-option
                  v-for="template in templates"
                  :key="template.template_code"
                  :label="template.template_name"
                  :value="template.template_code"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="启用状态">
              <el-select
                v-model="searchForm.is_active"
                placeholder="选择状态"
                clearable
                style="width: 120px"
                popper-class="batch-dialog-select-popper"
                popper-append-to-body
              >
                <el-option label="全部" value="" />
                <el-option label="激活" :value="1" />
                <el-option label="禁用" :value="0" />
              </el-select>
            </el-form-item>

            <el-form-item label="定时任务">
              <el-select
                v-model="searchForm.schedule_enabled"
                placeholder="选择状态"
                clearable
                style="width: 120px"
                popper-class="batch-dialog-select-popper"
                popper-append-to-body
              >
                <el-option label="全部" value="" />
                <el-option label="已启用" :value="1" />
                <el-option label="未启用" :value="0" />
              </el-select>
            </el-form-item>
          </div>

          <div class="search-form-actions">
            <el-button type="primary" @click="handleSearch" class="search-btn">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button type="warning" @click="handleReset" class="reset-btn">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
            <el-button type="success" @click="openCreateDialog">
              <el-icon><Plus /></el-icon>
              新增配置
            </el-button>
            <el-button
              :type="schedulerRunning ? 'warning' : 'success'"
              @click="handleToggleScheduler"
              :loading="schedulerLoading"
            >
              <el-icon><Setting /></el-icon>
              {{ schedulerRunning ? '停止调度器' : '启动调度器' }}
            </el-button>
          </div>
        </div>
      </el-form>
    </ReportsSearchCard>

    <ReportsTableCard>
      <template #title>
        <el-icon><Setting /></el-icon>
        <span>报表任务管理</span>
      </template>
      <template #actions>
        <el-button type="success" @click="handleRefresh" class="refresh-btn" :loading="loading" size="small">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
        <div class="table-info">
          <div class="pagination-control-wrapper clickable" @click="togglePagination">
            <span class="page-count">本页 {{ configs.length }} 条</span>
            <div class="divider"></div>
            <span class="pagination-info">
              {{ currentPage }}/{{ Math.ceil(total / pageSize) || 1 }}
            </span>
            <el-icon class="pagination-toggle-icon">
              <ArrowUp v-if="paginationVisible" />
              <ArrowDown v-else />
            </el-icon>
          </div>
        </div>
      </template>

      <el-table
        :data="configs"
        @sort-change="handleSortChange"
        :default-sort="{ prop: 'updated_at', order: 'descending' }"
        class="enhanced-table"
        style="width: 100%"
        :height="600"
        table-layout="fixed"
        :stripe="false"
        :border="false"
      >
        <el-table-column prop="config_name" label="报表标题" min-width="220" show-overflow-tooltip fixed="left">
          <template #default="{ row }">
            <div class="config-name">{{ row.config_name }}</div>
          </template>
        </el-table-column>

        <el-table-column label="报表模板" min-width="220" show-overflow-tooltip>
          <template #default="{ row }">
            <div class="template-name">{{ getTemplateName(row.template_code) }}</div>
          </template>
        </el-table-column>

        <el-table-column label="定时任务" min-width="220">
          <template #default="{ row }">
            <div v-if="row.schedule_enabled">
              <el-tag type="success" size="small">已启用</el-tag>
              <div class="cron-text" v-if="row.schedule_cron">
                <el-tooltip :content="'原始表达式：' + row.schedule_cron" placement="top">
                  <span>{{ getReadableCron(row.schedule_cron) }}</span>
                </el-tooltip>
              </div>
            </div>
            <el-tag v-else type="info" size="small">未启用</el-tag>
          </template>
        </el-table-column>

        <el-table-column label="输出格式" min-width="150">
          <template #default="{ row }">
            <el-tag
              v-for="format in getOutputFormats(row.output_formats)"
              :key="format"
              size="small"
              class="output-tag"
            >
              {{ format.toUpperCase() }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="通知" min-width="100" align="center">
          <template #default="{ row }">
            <el-tag v-if="row.notify_on_success" type="success" size="small">
              启用
            </el-tag>
            <el-tag v-else type="info" size="small">
              关闭
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="状态" min-width="100" align="center">
          <template #default="{ row }">
            <el-tag v-if="row.is_active" type="success" size="small">
              激活
            </el-tag>
            <el-tag v-else type="info" size="small">
              禁用
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="创建时间" min-width="180" show-overflow-tooltip sortable="custom" prop="created_at">
          <template #default="{ row }">
            {{ formatDateTime(row.created_at) }}
          </template>
        </el-table-column>

        <el-table-column label="更新时间" min-width="180" show-overflow-tooltip sortable="custom" prop="updated_at">
          <template #default="{ row }">
            {{ formatDateTime(row.updated_at) }}
          </template>
        </el-table-column>

        <el-table-column label="操作" width="220" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-tooltip content="查看历史" placement="top">
                <el-button
                  type="info"
                  size="small"
                  @click="handleViewHistory(row)"
                  circle
                >
                  <el-icon><Document /></el-icon>
                </el-button>
              </el-tooltip>
              <el-tooltip content="编辑配置" placement="top">
                <el-button
                  type="primary"
                  size="small"
                  @click="openEditDialog(row)"
                  circle
                >
                  <el-icon><Edit /></el-icon>
                </el-button>
              </el-tooltip>
              <el-tooltip content="立即运行" placement="top">
                <el-button
                  type="success"
                  size="small"
                  @click="openGenerateDialog(row)"
                  circle
                >
                  <el-icon><VideoPlay /></el-icon>
                </el-button>
              </el-tooltip>
              <el-tooltip content="更多操作" placement="top">
                <el-dropdown
                  @command="(command) => handleMoreAction(command, row)"
                  trigger="click"
                  popper-class="batch-dialog-select-popper"
                  popper-append-to-body
                >
                  <el-button type="info" size="small" circle>
                    <el-icon><MoreFilled /></el-icon>
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item command="detail">
                        <el-icon><View /></el-icon>
                        查看详情
                      </el-dropdown-item>
                      <el-dropdown-item command="delete" divided>
                        <el-icon><Delete /></el-icon>
                        <span class="danger-text">删除记录</span>
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <template #pagination>
        <transition name="pagination-slide">
          <div v-show="paginationVisible" class="pagination-section">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :total="total"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handlePageChange"
              background
              class="enhanced-pagination"
            />
          </div>
        </transition>
      </template>
    </ReportsTableCard>

    <el-dialog
      v-model="detailDialogVisible"
      width="900px"
      :close-on-click-modal="false"
      append-to-body
      class="unified-dialog"
    >
      <template #header>
        <DialogHeader
          :icon="View"
          title="配置详情"
          :description="detailDialogData?.config_name || ''"
          type="info"
        />
      </template>

      <div v-loading="detailDialogLoading">
        <el-descriptions :column="2" border v-if="detailDialogData">
          <el-descriptions-item label="报表标题">
            {{ detailDialogData.config_name || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="模板">
            {{ getTemplateName(detailDialogData.template_code) }}
          </el-descriptions-item>
          <el-descriptions-item label="启用状态">
            <el-tag :type="detailDialogData.is_active ? 'success' : 'info'" size="small">
              {{ detailDialogData.is_active ? '激活' : '禁用' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="通知">
            <el-tag :type="detailDialogData.notify_on_success ? 'success' : 'info'" size="small">
              {{ detailDialogData.notify_on_success ? '开启' : '关闭' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="输出格式" :span="2">
            <el-tag
              v-for="format in getOutputFormats(detailDialogData.output_formats)"
              :key="format"
              size="small"
              class="output-tag"
            >
              {{ format.toUpperCase() }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="定时任务" :span="2">
            <div v-if="detailDialogData.schedule_enabled">
              <el-tag type="success" size="small">已启用</el-tag>
              <div class="cron-display" v-if="detailDialogData.schedule_cron">
                <el-tooltip :content="'原始表达式：' + detailDialogData.schedule_cron" placement="top">
                  <span>{{ getReadableCron(detailDialogData.schedule_cron) }}</span>
                </el-tooltip>
              </div>
            </div>
            <el-tag v-else type="info" size="small">未启用</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="企业微信 Webhook" v-if="detailDialogData.wecom_webhook_id">
            {{ detailDialogData.wecom_webhook_id }}
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">
            {{ formatDateTime(detailDialogData.created_at) }}
          </el-descriptions-item>
          <el-descriptions-item label="更新时间">
            {{ formatDateTime(detailDialogData.updated_at) }}
          </el-descriptions-item>
        </el-descriptions>

        <div class="detail-section" v-if="detailDialogData?.params">
          <div class="section-header">
            <div class="section-title">参数配置</div>
            <div class="section-actions">
              <el-button
                text
                size="small"
                type="primary"
                @click="toggleParamJson"
              >
                <el-icon :class="['json-toggle-icon', { expanded: detailParamsExpanded }]">
                  <ArrowDown />
                </el-icon>
                {{ detailParamsExpanded ? '收起' : '展开' }}
              </el-button>
              <el-divider direction="vertical" class="json-action-divider" />
              <el-button
                text
                size="small"
                type="primary"
                @click="handleCopyJson(detailDialogData?.params, '参数配置')"
              >
                <el-icon><CopyDocument /></el-icon>
                复制
              </el-button>
            </div>
          </div>
          <transition name="json-collapse">
            <pre v-show="detailParamsExpanded" class="json-block">{{ formatJson(detailDialogData?.params) }}</pre>
          </transition>
          <div v-show="!detailParamsExpanded" class="json-collapsed-placeholder">
            JSON 内容较长，点击"展开"查看
          </div>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="detailDialogData && openEditDialog(detailDialogData)">
            编辑配置
          </el-button>
        </div>
      </template>
    </el-dialog>

    <ReportConfigEditDialog
      v-model="editDialogVisible"
      :config-id="editingConfigId"
      @saved="handleConfigSaved"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus, Setting, ArrowUp, ArrowDown, Document, Edit, VideoPlay, MoreFilled, View, Delete, CopyDocument } from '@element-plus/icons-vue'
import ReportsSearchCard from '../components/layout/ReportsSearchCard.vue'
import ReportsTableCard from '../components/layout/ReportsTableCard.vue'
import DialogHeader from '@/components/DialogHeader.vue'
import ReportConfigEditDialog from '../components/configs/ReportConfigEditDialog.vue'
import api from '@/utils/api'
import { createLogger } from '@/utils/logger'

const componentLogger = createLogger('ReportConfigsPage')
const router = useRouter()
const loading = ref(false)
const configs = ref([])
const templates = ref([])
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)
const paginationVisible = ref(false)
const schedulerRunning = ref(false)
const schedulerLoading = ref(false)
const detailDialogVisible = ref(false)
const detailDialogLoading = ref(false)
const detailDialogData = ref(null)
const detailParamsExpanded = ref(false)

const searchForm = reactive({
  template_code: '',
  is_active: '',
  schedule_enabled: '',
  sortField: 'updated_at',
  sortOrder: 'desc'
})

const fetchTemplates = async () => {
  try {
    const response = await api.get('/reports/templates', { params: { page: 1, size: 1000 } })
    templates.value = response.data.data.rows || []
    componentLogger.info('模板列表加载成功', { count: templates.value.length })
  } catch (error) {
    componentLogger.error('获取模板列表失败', error)
  }
}

const fetchConfigs = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      size: pageSize.value
    }

    if (searchForm.template_code) {
      params.template_code = searchForm.template_code
    }

    if (searchForm.is_active !== '') {
      params.is_active = searchForm.is_active === 1
    }

    if (searchForm.schedule_enabled !== '') {
      params.schedule_enabled = searchForm.schedule_enabled === 1
    }

    if (searchForm.sortField) {
      params.sort_field = searchForm.sortField
      params.sort_order = searchForm.sortOrder
    }

    const response = await api.get('/reports/configs', { params })
    configs.value = response.data.data.rows || []
    total.value = response.data.data.total || configs.value.length

    componentLogger.info('配置列表加载成功', {
      count: configs.value.length,
      total: total.value
    })
  } catch (error) {
    componentLogger.error('获取配置列表失败', error)
    ElMessage.error('获取配置列表失败')
  } finally {
    loading.value = false
  }
}

const getTemplateName = (code) => {
  const template = templates.value.find(t => t.template_code === code)
  return template ? template.template_name : code
}

const getReadableCron = (expr) => {
  if (!expr || typeof expr !== 'string') return '-'
  const parts = expr.trim().split(/\s+/)
  if (parts.length !== 5 && parts.length !== 6) return expr
  
  let second = '0', minute, hour, day, month, dow
  if (parts.length === 6) {
    [second, minute, hour, day, month, dow] = parts
  } else {
    [minute, hour, day, month, dow] = parts
  }
  
  const any = (v) => v === '*' || v === '*/1'
  const isNumber = (v) => /^\d+$/.test(v)
  
  try {
    // 工作日判断 (1-5)
    if (dow === '1-5' && any(day) && any(month)) {
      return `工作日 ${hour}点${minute}分运行`
    }
    
    // 每周几判断
    if (isNumber(dow) && any(day) && any(month)) {
      const weekdays = ['日', '一', '二', '三', '四', '五', '六']
      const weekday = weekdays[parseInt(dow)] || dow
      return `每周${weekday} ${hour}点${minute}分运行`
    }
    
    // 每月几号
    if (isNumber(day) && any(month) && any(dow)) {
      return `每月${day}日 ${hour}点${minute}分运行`
    }
    
    // 每年几月几号
    if (isNumber(month) && isNumber(day)) {
      return `每年${month}月${day}日 ${hour}点${minute}分运行`
    }
    
    // 每天几点几分
    if (any(day) && any(month) && any(dow) && isNumber(hour) && isNumber(minute)) {
      return `每天 ${hour}点${minute}分运行`
    }
    
    // 每小时第几分钟
    if (any(day) && any(month) && any(dow) && any(hour) && isNumber(minute)) {
      return `每小时第${minute}分运行`
    }
    
    // 每N小时
    if (hour && hour.startsWith('*/') && any(day) && any(month) && any(dow) && minute === '0') {
      const n = hour.replace('*/', '')
      return `每${n}小时运行`
    }
    
    // 每N分钟
    if (minute && minute.startsWith('*/') && any(day) && any(month) && any(dow) && any(hour)) {
      const n = minute.replace('*/', '')
      return `每${n}分钟运行`
    }
    
    // 每小时
    if (any(day) && any(month) && any(dow) && any(hour) && minute === '0') {
      return '每小时运行'
    }
    
    // 每天0点
    if (any(day) && any(month) && any(dow) && hour === '0' && minute === '0') {
      return '每天 0点运行'
    }
  } catch (e) {
    return expr
  }
  
  return expr
}

const getOutputFormats = (formats) => {
  if (!formats) return []
  if (typeof formats === 'string') {
    try {
      return JSON.parse(formats)
    } catch {
      return []
    }
  }
  return formats
}

const formatJson = (value) => {
  if (!value) return '-'
  let payload = value
  if (typeof value === 'string') {
    try {
      payload = JSON.parse(value)
    } catch (error) {
      return value
    }
  }
  try {
    return JSON.stringify(payload, null, 2)
  } catch (error) {
    return '-'
  }
}

const formatDateTime = (dateTimeStr) => {
  if (!dateTimeStr) return '-'

  if (/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/.test(dateTimeStr)) {
    return dateTimeStr
  }

  if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/.test(dateTimeStr) && !dateTimeStr.includes('Z') && !dateTimeStr.match(/[+-]\d{2}:\d{2}$/)) {
    const match = dateTimeStr.match(/^(\d{4}-\d{2}-\d{2})T(\d{2}:\d{2}:\d{2})/)
    if (match) {
      return `${match[1]} ${match[2]}`
    }
  }

  try {
    const date = new Date(dateTimeStr)
    if (isNaN(date.getTime())) {
      return dateTimeStr
    }

    const formatter = new Intl.DateTimeFormat('zh-CN', {
      timeZone: 'Asia/Shanghai',
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit',
      hour12: false
    })

    const parts = formatter.formatToParts(date)
    const year = parts.find(p => p.type === 'year').value
    const month = parts.find(p => p.type === 'month').value
    const day = parts.find(p => p.type === 'day').value
    const hour = parts.find(p => p.type === 'hour').value
    const minute = parts.find(p => p.type === 'minute').value
    const second = parts.find(p => p.type === 'second').value

    return `${year}-${month}-${day} ${hour}:${minute}:${second}`
  } catch (error) {
    return dateTimeStr
  }
}

const handleSearch = () => {
  currentPage.value = 1
  fetchConfigs()
}

const handleReset = () => {
  searchForm.template_code = ''
  searchForm.is_active = ''
  searchForm.schedule_enabled = ''
  searchForm.sortField = 'updated_at'
  searchForm.sortOrder = 'desc'
  currentPage.value = 1
  fetchConfigs()
}

const handleRefresh = () => {
  fetchConfigs()
  fetchTemplates()
  fetchSchedulerStatus()
  ElMessage.success('刷新成功')
}

const handleSizeChange = () => {
  currentPage.value = 1
  fetchConfigs()
}

const handlePageChange = () => {
  fetchConfigs()
}

const handleSortChange = ({ prop, order }) => {
  if (prop) {
    searchForm.sortField = prop
    searchForm.sortOrder = order === 'ascending' ? 'asc' : 'desc'
    fetchConfigs()
  }
}

const togglePagination = () => {
  paginationVisible.value = !paginationVisible.value
}

const handleViewHistory = (row) => {
  router.push({
    path: '/reports',
    query: {
      tab: 'history',
      report_config_id: row.id
    }
  })
}

const editDialogVisible = ref(false)
const editingConfigId = ref(null)

const openCreateDialog = () => {
  editingConfigId.value = null
  editDialogVisible.value = true
}

const openEditDialog = (row) => {
  if (!row?.id) return
  editingConfigId.value = row.id
  editDialogVisible.value = true
}

const openGenerateDialog = async (row) => {
  if (!row?.id) return
  try {
    loading.value = true
    const response = await api.get(`/reports/configs/${row.id}`)
    const config = response.data.data
    
    if (!config) {
      ElMessage.error('未找到配置详情')
      return
    }
    
    // 解析 params（如果它是字符串）
    const params = typeof config.params === 'string' ? JSON.parse(config.params) : config.params
    
    // 使用config_name作为标题
    const title = config.config_name || null
    
    const generateResponse = await api.post('/reports/generate', {
      template_code: config.template_code,
      config_id: row.id,  // 传递配置ID，用于关联报表运行记录
      title: title,  // 使用config_name作为标题
      params: params,
      output_formats: config.output_formats,
      notify_params: config.notify_on_success ? {
        send_notification: true
      } : null
    })
    
    ElMessage.success('报表生成任务已提交')
    componentLogger.info('立即运行配置', { config_id: row.id })
    
    // 获取返回的 run_id 并跳转到报表历史
    if (generateResponse.data.success && generateResponse.data.data?.run_id) {
      const runId = generateResponse.data.data.run_id
      router.push({
        path: '/reports',
        query: {
          tab: 'history',
          run_id: runId
        }
      })
      componentLogger.info('跳转到报表历史', { run_id: runId })
    }
  } catch (error) {
    componentLogger.error('运行配置失败', error)
    ElMessage.error(error.response?.data?.message || '运行失败')
  } finally {
    loading.value = false
  }
}

const handleConfigSaved = () => {
  fetchConfigs()
  fetchTemplates()
}

// 监听对话框关闭，清空 editingConfigId 确保下次打开时能正确加载
watch(
  () => editDialogVisible.value,
  (visible) => {
    if (!visible) {
      // 对话框关闭时清空 editingConfigId，确保下次打开时能正确加载数据
      editingConfigId.value = null
    }
  }
)

const handleMoreAction = (command, row) => {
  switch (command) {
    case 'detail':
      handleViewDetail(row)
      break
    case 'delete':
      handleDelete(row)
      break
    default:
      componentLogger.warn('未知操作', { command, rowId: row?.id })
  }
}

const handleViewDetail = async (row) => {
  if (!row?.id) return
  detailDialogLoading.value = true
  detailParamsExpanded.value = false
  try {
    const response = await api.get(`/reports/configs/${row.id}`)
    detailDialogData.value = response.data.data
    detailDialogVisible.value = true
    componentLogger.info('查看配置详情', { config_id: row.id })
  } catch (error) {
    componentLogger.error('获取配置详情失败', error)
    ElMessage.error('获取配置详情失败')
  } finally {
    detailDialogLoading.value = false
  }
}

const handleCopyJson = async (json, label) => {
  const text = formatJson(json)
  try {
    await navigator.clipboard.writeText(text)
    ElMessage.success(`${label} JSON 已复制`)
  } catch (error) {
    componentLogger.error('复制 JSON 失败', error)
    ElMessage.error('复制失败，请手动复制')
  }
}

const toggleParamJson = () => {
  detailParamsExpanded.value = !detailParamsExpanded.value
}

const handleDelete = async (row) => {
  if (!row?.id) return
  try {
    await ElMessageBox.confirm(
      `确定要删除报表标题 "${row.config_name}" 的配置吗？此操作不可恢复。`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await api.delete(`/reports/configs/${row.id}`)
    ElMessage.success('删除成功')
    componentLogger.info('配置删除成功', { config_id: row.id })
    fetchConfigs()
  } catch (error) {
    if (error !== 'cancel') {
      componentLogger.error('删除配置失败', error)
      ElMessage.error(error.response?.data?.message || '删除失败')
    }
  }
}

const fetchSchedulerStatus = async () => {
  try {
    const response = await api.get('/reports/scheduler/status')
    schedulerRunning.value = !!response.data?.data?.scheduler_running
  } catch (error) {
    componentLogger.warn('获取调度器状态失败', error)
  }
}

const handleToggleScheduler = async () => {
  if (schedulerLoading.value) return
  schedulerLoading.value = true
  const previous = schedulerRunning.value
  try {
    if (schedulerRunning.value) {
      const response = await api.post('/reports/scheduler/stop')
      schedulerRunning.value = !!response.data?.data?.scheduler_running
      ElMessage.success(response.data?.message || '调度器已停止')
    } else {
      const response = await api.post('/reports/scheduler/start')
      schedulerRunning.value = !!response.data?.data?.scheduler_running
      ElMessage.success(response.data?.message || '调度器已启动')
    }
  } catch (error) {
    schedulerRunning.value = previous
    componentLogger.error('调度器切换失败', error)
    ElMessage.error(error.response?.data?.message || '操作失败')
  } finally {
    schedulerLoading.value = false
  }
}

onMounted(() => {
  fetchTemplates()
  fetchConfigs()
  fetchSchedulerStatus()
})
</script>

<style scoped>
.report-configs-page {
  padding: 0;
}

.search-form-content {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 20px;
}

.search-form-fields {
  display: flex;
  gap: 20px;
  flex: 1;
}

.search-form-fields .el-form-item {
  margin-bottom: 0;
}

.search-form-actions {
  display: flex;
  gap: 10px;
  white-space: nowrap;
}

.config-name {
  font-weight: 500;
}

.template-name {
  font-weight: 500;
}

.cron-text {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
}

.output-tag {
  margin-right: 4px;
}

.table-info {
  display: flex;
  align-items: center;
}

.refresh-btn {
  background: linear-gradient(135deg, #67C23A 0%, #85CE61 100%);
  border: none;
  border-radius: 8px;
  color: #fff;
  box-shadow: 0 4px 12px rgba(103, 194, 58, 0.3);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  font-weight: 500;
}

.refresh-btn:hover {
  background: linear-gradient(135deg, #85CE61 0%, #67C23A 100%);
  box-shadow: 0 6px 20px rgba(103, 194, 58, 0.4);
  transform: translateY(-2px);
  color: #fff;
}

.pagination-control-wrapper {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 4px 8px;
  background: rgba(64, 158, 255, 0.08);
  border: 1px solid rgba(64, 158, 255, 0.2);
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  user-select: none;
  font-size: 12px;
  height: 24px;
}

.pagination-control-wrapper:hover {
  background: rgba(64, 158, 255, 0.12);
  border-color: rgba(64, 158, 255, 0.3);
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.15);
}

.page-count {
  font-size: 12px;
  font-weight: 500;
  color: #909399;
  line-height: 1;
}

.divider {
  width: 1px;
  height: 12px;
  background: rgba(64, 158, 255, 0.3);
  margin: 0 2px;
}

.pagination-info {
  font-size: 12px;
  font-weight: 500;
  color: #409eff;
  letter-spacing: 0.5px;
  min-width: 24px;
  text-align: center;
  line-height: 1;
}

.pagination-toggle-icon {
  font-size: 12px;
  color: #409eff;
  transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.pagination-section {
  padding: 16px;
  border-top: 1px solid #f0f0f0;
  background: #fafafa;
}

.pagination-section .el-pagination {
  display: flex;
  justify-content: center;
}

.pagination-slide-enter-active,
.pagination-slide-leave-active {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.pagination-slide-enter-from,
.pagination-slide-leave-to {
  opacity: 0;
  max-height: 0;
  overflow: hidden;
}

.pagination-slide-enter-to,
.pagination-slide-leave-from {
  opacity: 1;
  max-height: 200px;
}

.action-buttons {
  display: flex;
  gap: 12px;  /* 基础间距：12px */
  flex-wrap: nowrap;
  white-space: nowrap;
  justify-content: flex-start;
  align-items: center;
}

/* 确保所有包装元素不影响间距 - 只重置上下和右的 margin，保留左 margin 用于控制间距 */
.action-buttons > * {
  margin-top: 0 !important;
  margin-bottom: 0 !important;
  margin-right: 0 !important;
  margin-left: 0;
  padding: 0;
  display: inline-flex;
}

/* 确保 el-tooltip 包装元素不影响间距 */
.action-buttons > :deep(.el-tooltip) {
  display: inline-flex;
  margin-top: 0 !important;
  margin-bottom: 0 !important;
  margin-right: 0 !important;
  margin-left: 0;
  padding: 0;
}

.action-buttons :deep(.el-tooltip__trigger) {
  display: inline-flex;
  margin: 0 !important;
  padding: 0;
}

/* 确保 el-dropdown 不影响间距 */
.action-buttons :deep(.el-dropdown) {
  display: inline-flex;
  margin: 0 !important;
  padding: 0;
}

/* 为第4个按钮（更多操作）添加额外左边距，使其与前3个按钮有更明显的视觉分隔 */
/* 这样前3个按钮之间是 12px（gap），第3个和第4个之间是 12px（gap）+ 8px（margin）= 20px */
.action-buttons > :nth-child(4) {
  margin-left: 8px !important;
}

.action-buttons :deep(.el-button) {
  font-weight: 500;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.12);
  width: 32px;
  height: 32px;
  padding: 0;
  display: inline-flex;
  align-items: center;
  justify-content: center;
}

.action-buttons :deep(.el-button:hover) {
  transform: translateY(-2px) scale(1.05);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
}

.action-buttons :deep(.el-button:active) {
  transform: translateY(0) scale(0.98);
}

.action-buttons :deep(.el-button--primary) {
  background: linear-gradient(135deg, #409EFF 0%, #66B3FF 100%);
  border: none;
}

.action-buttons :deep(.el-button--success) {
  background: linear-gradient(135deg, #67C23A 0%, #85CE61 100%);
  border: none;
}

.action-buttons :deep(.el-button--info) {
  background: linear-gradient(135deg, #909399 0%, #B1B3B8 100%);
  border: none;
}

/* 下拉菜单内部按钮样式 */
.action-buttons :deep(.el-dropdown .el-button) {
  width: 32px;
  height: 32px;
  padding: 0;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  margin: 0;
}

.danger-text {
  color: #f56c6c;
}

.detail-section {
  margin-top: 24px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.section-title {
  font-weight: 600;
  color: #303133;
}

.section-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}

.json-block {
  max-height: 260px;
  overflow: auto;
  background: #f5f5f5;
  padding: 10px;
  border-radius: 4px;
  font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, monospace;
  font-size: 13px;
}

.json-collapsed-placeholder {
  padding: 12px;
  background: #f8f9fb;
  border: 1px dashed #dcdfe6;
  border-radius: 4px;
  color: #909399;
  font-size: 13px;
}

.json-action-divider {
  height: 20px;
  margin: 0 4px;
}

.json-toggle-icon {
  transition: transform 0.2s ease;
}

.json-toggle-icon.expanded {
  transform: rotate(180deg);
}

.json-collapse-enter-active,
.json-collapse-leave-active {
  transition: max-height 0.3s ease, opacity 0.3s ease;
}

.json-collapse-enter-from,
.json-collapse-leave-to {
  max-height: 0;
  opacity: 0;
}

.json-collapse-enter-to,
.json-collapse-leave-from {
  max-height: 400px;
  opacity: 1;
}

.cron-display {
  font-size: 12px;
  color: #666;
  margin-top: 4px;
}
</style>
